package com.example.restatr;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Adapter.CardAdapter;
import com.example.restatr.Adapter.ViewPagerAdapter;
import com.example.restatr.Adapter.NewsAdapter;
import com.example.restatr.Atcivity.Main.LoginAt;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Bean.CardBean;
import com.example.restatr.Atcivity.Main.Fragment.NewsFragment;
import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class Tools {
    public static String ip = "http://218.7.112.123:10001/";
    private Toast toast;
    public static OkHttpClient okHttpClient = new OkHttpClient();


    public static String Get(String link, String token) {
        String jg = null;
        try {
            Request builder = new Request.Builder()
                    .get()
                    .header("Authorization", token)
                    .url(ip + link)
                    .build();
            jg = okHttpClient.newCall(builder).execute().body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jg;
    }

    public static String Put(String link, String token, String jsonObject) {
        String jg = null;
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject);
            Request builder = new Request.Builder()
                    .put(requestBody)
                    .header("Authorization", token)
                    .url(ip + link)
                    .build();
            jg = okHttpClient.newCall(builder).execute().body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jg;
    }


    public static String Post(String link, String token, String content) {
        String jg = null;
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), content);
            Request builder = new Request.Builder()
                    .post(requestBody)
                    .header("Authorization", token)
                    .url(ip + link)
                    .build();
            jg = okHttpClient.newCall(builder).execute().body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jg;
    }

    public static String UploadFiles(String link, String token, File file) {
        String jg = null;
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody mB = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), requestBody)
                    .build();
            Request builder = new Request.Builder()
                    .post(mB)
                    .header("Authorization", token)
                    .url(ip + link)
                    .build();
            jg = okHttpClient.newCall(builder).execute().body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jg;
    }

    public static String Delete(String link, String token) {
        String jg = null;
        try {
            Request builder = new Request.Builder()
                    .delete()
                    .header("Authorization", token)
                    .url(ip + link)
                    .build();
            jg = okHttpClient.newCall(builder).execute().body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jg;
    }

    public static void ShowToast(Context context, String text) {
        Toast toast = null;
        if (toast == null) {
            toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        } else {
            toast.setText(text);
            toast.setDuration(Toast.LENGTH_SHORT);
        }
        toast.show();
    }

    //设置toolBar
    public static void SetBarTitle(Toolbar toolbar, TextView title, String titleText, EditText searchView, Context context, boolean isOpen) {
        toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_24);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity) context).finish();
            }
        });
        title.setVisibility(View.VISIBLE);
        title.setText(titleText);
        searchView.setVisibility(View.GONE);
        if (!isOpen) {
            toolbar.getMenu().clear();
        }
    }
    //设置轮播图
    public static void SetBanner(String link, String token, String rowsName, String imgUrl, String title, Banner banner, Context context) {
        List<String> imgUrls = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        ImageLoader imageLoader = new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(context)
                        .load(Tools.ip + o)
                        .transform(new RoundedCorners(15))
                        .into(imageView);
            }
        };
        new Thread(() -> {
            try {
                String get = Tools.Get(link, token);
                JSONObject jx = new JSONObject(get);
                JSONArray rows = jx.getJSONArray(rowsName);
                for (int i = 0; i < rows.length(); i++) {
                    JSONObject all = rows.getJSONObject(i);
                    imgUrls.add(all.getString(imgUrl));
                    titles.add(all.getString(title));
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                                .setImageLoader(imageLoader)
                                .setImages(imgUrls)
                                .setIndicatorGravity(BannerConfig.CENTER)
                                .start();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }
    public static void SetBanner(String link, String token, String rowsName, String imgUrl,Banner banner,Context context) {
        List<String> imgUrls = new ArrayList<>();
        ImageLoader imageLoader = new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(context)
                        .load(Tools.ip + o)
                        .transform(new RoundedCorners(15))
                        .into(imageView);
            }
        };
        new Thread(() -> {
            try {
                String get = Tools.Get(link, token);
                JSONObject jx = new JSONObject(get);
                JSONArray rows = jx.getJSONArray(rowsName);
                for (int i = 0; i < rows.length(); i++) {
                    JSONObject all = rows.getJSONObject(i);
                    imgUrls.add(all.getString(imgUrl));
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                                .setImageLoader(imageLoader)
                                .setImages(imgUrls)
                                .setIndicatorGravity(BannerConfig.CENTER)
                                .start();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //获取轮播图
    public static void SetRbt(String link, String token, String type, String fieldName, Context context, List<ImageView> imageViews, ViewPager viewPager, LinearLayout group, int width) {
        List<ImageView> zsqs = new ArrayList<>();
        zsqs.clear();
        new Thread(() -> {
            String get = Tools.Get(link, token);
            if (get != null) {
                String finalGet = get;
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jx = new JSONObject(finalGet);
                            JSONArray rows = jx.getJSONArray(type);
                            for (int i = 0; i < rows.length(); i++) {
                                JSONObject all = rows.getJSONObject(i);
                                ImageView imageView = new ImageView(context);
                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                Glide.with(context)
                                        .load(Tools.ip + all.getString(fieldName))
                                        .transform(new RoundedCorners(15))
                                        .into(imageView);
                                imageViews.add(imageView);
                            }
                            //动态添加指示器
                            ImageView zsq;
                            for (int i = 0; i < imageViews.size(); i++) {
                                zsq = new ImageView(context);
                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, 25, 1);
                                layoutParams.setMargins(15, 0, 15, 0);
                                zsq.setLayoutParams(layoutParams);
                                zsqs.add(zsq);
                                if (i == 0) {
                                    zsqs.get(i).setBackgroundResource(R.drawable.select_yuan);
                                } else {
                                    zsqs.get(i).setBackgroundResource(R.drawable.no_select_yuan);
                                }
                                group.addView(zsqs.get(i));
                            }
                            viewPager.setAdapter(new ViewPagerAdapter(imageViews));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            while (get == null) {
                get = Tools.Get(link, token);
                if (get != null) {
                    String finalGet1 = get;
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jx = new JSONObject(finalGet1);
                                JSONArray rows = jx.getJSONArray(type);
                                for (int i = 0; i < rows.length(); i++) {
                                    JSONObject all = rows.getJSONObject(i);
                                    ImageView imageView = new ImageView(context);
                                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                    Glide.with(context)
                                            .load(Tools.ip + all.getString(fieldName))
                                            .transform(new RoundedCorners(15))
                                            .into(imageView);
                                    imageViews.add(imageView);
                                }
                                //动态添加指示器
                                ImageView zsq;
                                for (int i = 0; i < imageViews.size(); i++) {
                                    zsq = new ImageView(context);
                                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, 25, 1);
                                    layoutParams.setMargins(15, 0, 15, 0);
                                    zsq.setLayoutParams(layoutParams);
                                    zsqs.add(zsq);
                                    if (i == 0) {
                                        zsqs.get(i).setBackgroundResource(R.drawable.select_yuan);
                                    } else {
                                        zsqs.get(i).setBackgroundResource(R.drawable.no_select_yuan);
                                    }
                                    group.addView(zsqs.get(i));
                                }
                                viewPager.setAdapter(new ViewPagerAdapter(imageViews));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }).start();
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < zsqs.size(); i++) {
                    if (i == position) {
                        zsqs.get(i).setBackgroundResource(R.drawable.select_yuan);
                    } else {
                        zsqs.get(i).setBackgroundResource(R.drawable.no_select_yuan);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //设置分类卡片
    public static void SetCard(String link, String token, String type, String rowsName, String fieldNameId, String fieldNameUrl, String fieldNameTitle, Context context, List<CardBean> cardBeans, GridView card) {
        new Thread(() -> {
            String get = Tools.Get(link, token);
            if (get != null) {
                String finalGet = get;
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jx = new JSONObject(finalGet);
                            JSONArray rows = jx.getJSONArray(rowsName);
                            for (int i = 0; i < rows.length(); i++) {
                                JSONObject all = rows.getJSONObject(i);
                                cardBeans.add(new CardBean(all.getString(fieldNameUrl), all.getString(fieldNameTitle), all.getString(fieldNameId)));
                                card.setAdapter(new CardAdapter(type, context, cardBeans));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            while (get == null) {
                get = Tools.Get(link, token);
                if (get != null) {
                    String finalGet1 = get;
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jx = new JSONObject(finalGet1);
                                JSONArray rows = jx.getJSONArray(rowsName);
                                for (int i = 0; i < rows.length(); i++) {
                                    JSONObject all = rows.getJSONObject(i);
                                    cardBeans.add(new CardBean(all.getString(fieldNameUrl), all.getString(fieldNameTitle), all.getString(fieldNameId)));
                                    card.setAdapter(new CardAdapter(type, context, cardBeans));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }).start();
    }

    //轮播图定时切换
    public static void TimerSwitch(Context context, ViewPager rbt, List<ImageView> imageViews) {
        if (context != null) {
            ((Activity) context).runOnUiThread(() -> {
                if (rbt.getCurrentItem() == imageViews.size() - 1) {
                    rbt.setCurrentItem(0);
                } else {
                    rbt.setCurrentItem(rbt.getCurrentItem() + 1);
                }
            });
        }
    }

    //获取新闻分类
    public static void GetXwFl(String link, String token, Context context, String rowsName, List<String> tabTitle, List<String> tabId, List<Fragment> fragments, ViewPager XwPager, TabLayout tab, FragmentManager fragmentManager) {
        //获取新闻类别
        new Thread(new Runnable() {
            @Override
            public void run() {
                String tabList = Tools.Get(link, token);
                if (context != null & tabList != null) {
                    String finalTabList = tabList;
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jx = new JSONObject(finalTabList);
                                JSONArray data = jx.getJSONArray(rowsName);
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject all = data.getJSONObject(i);
                                    tabTitle.add(all.getString("name"));
                                    tabId.add(all.getString("id"));
                                    fragments.add(new NewsFragment());
                                }
                                XwPager.setOffscreenPageLimit(tabTitle.size());
                                tab.setupWithViewPager(XwPager);
                                if (fragmentManager != null) {
                                    XwPager.setAdapter(new NewsAdapter(fragmentManager, fragments, tabTitle));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                while (tabList == null) {
                    tabList = Tools.Get(link, "");
                    if (context != null & tabList != null) {
                        String finalTabList1 = tabList;
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jx = new JSONObject(finalTabList1);
                                    JSONArray data = jx.getJSONArray(rowsName);
                                    for (int i = 0; i < data.length(); i++) {
                                        JSONObject all = data.getJSONObject(i);
                                        tabTitle.add(all.getString("name"));
                                        tabId.add(all.getString("id"));
                                        fragments.add(new NewsFragment());
                                    }
                                    XwPager.setOffscreenPageLimit(tabTitle.size());
                                    tab.setupWithViewPager(XwPager);
                                    if (fragmentManager != null) {
                                        XwPager.setAdapter(new NewsAdapter(fragmentManager, fragments, tabTitle));
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }
        }).start();
    }

    //设置性别
    public static String SetSex(String sex) {
        String jg = "";
        if (sex.equals("0")) {
            jg = "男";
        } else if (sex.equals("1")) {
            jg = "女";
        }
        return jg;
    }

    //判断文本是否为空
    public static boolean isEmptyText(TextView editText) {
        return !TextUtils.isEmpty(editText.getText().toString().trim());
    }

    //跳转页面前，判断是否登入
    public static void StartActivity(Context context, Class cl) {
        if (MainActivity.sp.getInt("code", 0) == 200) {
            context.startActivity(new Intent(context, cl));
        } else {
            Toast.makeText(context, "您还未登入！", Toast.LENGTH_SHORT).show();
            context.startActivity(new Intent(context, LoginAt.class));
        }
    }

    public static void GetLevel(float score, TextView textView) {
        if (score >= 4) {
            textView.setText("非常满意");
        } else if (score >= 3 && score < 4) {
            textView.setText("满意");
        } else if (score >= 2 && score < 3) {
            textView.setText("差");
        } else if (score < 2) {
            textView.setText("非常差");
        }
    }

}
